package com.luoxiang.socialandroid.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.view.*
import com.luoxiang.socialandroid.R
import com.luoxiang.socialandroid.activity.TestActivity
import com.luoxiang.socialandroid.app.MyAppliaction
import com.netease.lava.nertc.sdk.video.NERtcVideoView
import com.netease.yunxin.nertc.nertcvideocall.model.NERTCVideoCall


class FloatVideoWindowService : Service() {
    private var mWindowManager: WindowManager? = null
    private var wmParams: WindowManager.LayoutParams? = null
    private var inflater: LayoutInflater? = null
    private var currentBigUserId: String? = null

    //浮动布局view
    private var mFloatingLayout: View? = null

    //容器父布局
    private var mVideoViewRemote: NERtcVideoView? = null
    override fun onCreate() {
        super.onCreate()
        initWindow() //设置悬浮窗基本参数（位置、宽高等
        startNotification()
    }

    private fun startNotification() {
        val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        val channel: NotificationChannel?
        val notification: Notification?
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            channel =
                NotificationChannel("10001", "通话中", NotificationManager.IMPORTANCE_LOW)
            channel.enableLights(true)
            channel.lightColor = Color.RED
            channel.setShowBadge(true)
            channel.description = "PowerStateService"
            channel.lockscreenVisibility =
                Notification.VISIBILITY_PUBLIC //设置锁屏可见 VISIBILITY_PUBLIC=可见
            manager.createNotificationChannel(channel)
            notification = Notification.Builder(this)
                .setChannelId("10001")
                .setContentTitle("通话正在进行中") //标题
                .setContentText("通话正在进行中") //内容
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.lanuchimage) //小图标一定需要设置,否则会报错(如果不设置它启动服务前台化不会报错,但是你会发现这个通知不会启动),如果是普通通知,不设置必然报错
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.mipmap.lanuchimage))
                .build()
            startForeground(1, notification) //服务前台化只能使用startForeground()方法,不能使用 notificationManager.notify(1,notification); 这个只是启动通知使用的,使用这个方法你只需要等待几秒就会发现报错了
        }
    }


    override fun onBind(intent: Intent): IBinder {
        currentBigUserId = intent.getStringExtra("userId")
        initFloating() //悬浮框点击事件的处理
        return FloatVideoWindowBinder()
    }

    inner class FloatVideoWindowBinder : Binder() {
        val service: FloatVideoWindowService
            get() = this@FloatVideoWindowService
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mFloatingLayout != null) {
            // 移除悬浮窗口
            mWindowManager!!.removeView(mFloatingLayout)
            mFloatingLayout = null
        }
    }

    /**
     * 设置悬浮框基本参数（位置、宽高等）
     */
    private fun initWindow() {
        mWindowManager = applicationContext.getSystemService(WINDOW_SERVICE) as WindowManager
        //设置好悬浮窗的参数
        wmParams = getWmParams()
        // 悬浮窗默认显示以左上角为起始坐标
        wmParams!!.gravity = Gravity.START or Gravity.TOP
        //悬浮窗的开始位置，因为设置的是从左上角开始，所以屏幕左上角是x=0;y=0
        wmParams!!.x = 70
        wmParams!!.y = 210
        //得到容器，通过这个inflater来获得悬浮窗控件
        inflater = LayoutInflater.from(applicationContext)
        // 获取浮动窗口视图所在布局
        mFloatingLayout = inflater?.inflate(R.layout.alert_float_video_layout, null)
        // 添加悬浮窗的视图
        mWindowManager!!.addView(mFloatingLayout, wmParams)
    }

    private fun getWmParams(): WindowManager.LayoutParams? {
        wmParams = WindowManager.LayoutParams()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            wmParams!!.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            wmParams!!.type = WindowManager.LayoutParams.TYPE_PHONE
        }
        //设置可以显示在状态栏上
        wmParams!!.flags =
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED

        //设置悬浮窗口长宽数据
        wmParams!!.width = WindowManager.LayoutParams.WRAP_CONTENT
        wmParams!!.height = WindowManager.LayoutParams.WRAP_CONTENT
        return wmParams
    }

    private fun initFloating() {
        mVideoViewRemote = mFloatingLayout?.findViewById(R.id.videoViewRemote)
        //悬浮框触摸事件，设置悬浮框可拖动
        mVideoViewRemote?.setOnTouchListener(FloatingListener())
        //悬浮框点击事件
        mVideoViewRemote?.setOnClickListener {
            val activity =
                MyAppliaction.getMyAppliaction().activities.get(MyAppliaction.getMyAppliaction().activities.size - 1)
            activity.startActivity(Intent(activity, TestActivity::class.java))
        }
    }

    fun setVideoViewRemote(nertcVideoCall: NERTCVideoCall) {
        nertcVideoCall.setupRemoteView(mVideoViewRemote, currentBigUserId)
    }

    //开始触控的坐标，移动时的坐标（相对于屏幕左上角的坐标）
    private var mTouchStartX = 0
    private var mTouchStartY = 0
    private var mTouchCurrentX = 0
    private var mTouchCurrentY = 0

    //开始时的坐标和结束时的坐标（相对于自身控件的坐标）
    private var mStartX = 0
    private var mStartY = 0
    private var mStopX = 0
    private var mStopY = 0

    //判断悬浮窗口是否移动，这里做个标记，防止移动后松手触发了点击事件
    private var isMove = false

    private inner class FloatingListener : View.OnTouchListener {
        override fun onTouch(v: View?, event: MotionEvent): Boolean {
            val action = event.action
            when (action) {
                MotionEvent.ACTION_DOWN -> {
                    isMove = false
                    mTouchStartX = event.rawX.toInt()
                    mTouchStartY = event.rawY.toInt()
                    mStartX = event.x.toInt()
                    mStartY = event.y.toInt()
                }
                MotionEvent.ACTION_MOVE -> {
                    mTouchCurrentX = event.rawX.toInt()
                    mTouchCurrentY = event.rawY.toInt()
                    wmParams!!.x += mTouchCurrentX - mTouchStartX
                    wmParams!!.y += mTouchCurrentY - mTouchStartY
                    mWindowManager!!.updateViewLayout(mFloatingLayout, wmParams)
                    mTouchStartX = mTouchCurrentX
                    mTouchStartY = mTouchCurrentY
                }
                MotionEvent.ACTION_UP -> {
                    mStopX = event.x.toInt()
                    mStopY = event.y.toInt()
                    if (Math.abs(mStartX - mStopX) >= 1 || Math.abs(mStartY - mStopY) >= 1) {
                        isMove = true
                    }
                }
                else -> {}
            }
            //如果是移动事件不触发OnClick事件，防止移动的时候一放手形成点击事件
            return isMove
        }
    }
}